﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace UnityView
{
    public class UIBoard : IViewLayout
    {
        public GameObject UIObject;

        protected Canvas Canvas;

        public CanvasScaler CanvasScaler { get; protected set; }

        public float DynamicPixelsPerUnit
        {
            set { CanvasScaler.dynamicPixelsPerUnit = value; }
            get { return CanvasScaler.dynamicPixelsPerUnit; }
        }

        protected GraphicRaycaster GraphicRaycaster;

        public readonly List<IViewLayout> Subviews = new List<IViewLayout>();

        public UIBoard(Vector2 size, string name = "UI Board") : this(Vector3.zero, size, name)
        {
        }

        public UIBoard(Vector3 position, Vector2 size, string name = "UIView Board") :
            this(Camera.main, position, size, null, name)
        {
        }

        public UIBoard(Vector3 position, Vector2 size, Transform parent, string name = "UIView Board") :
            this(Camera.main, position, size, parent, name)
        {
        }

        public UIBoard(Camera camera, Vector3 position, Vector2 size, Transform parent, string name = "UI Board")
        {
            Width = size.x;
            Height = size.y;

            UIObject = new GameObject(name)
            {
                layer = UIConstant.LayerDefault
            };
            RectTransform = UIObject.AddComponent<RectTransform>();
            if (parent != null) RectTransform.SetParent(parent);
            RectTransform.pivot = new Vector2(0.5f, 0);
            RectTransform.position = position;
            RectTransform.sizeDelta = size;

            Canvas = UIObject.AddComponent<Canvas>();
            Canvas.renderMode = RenderMode.WorldSpace;
            Canvas.worldCamera = camera;

            CanvasScaler = UIObject.AddComponent<CanvasScaler>();
            GraphicRaycaster = UIObject.AddComponent<GraphicRaycaster>();
        }

        public Canvas GetCanvas()
        {
            return Canvas;
        }

        public GraphicRaycaster GetGraphicRaycaster()
        {
            return GraphicRaycaster;
        }

        public float Width { get; }
        public float Height { get; }
        public RectTransform RectTransform { get; }
        public IViewLayout ParentView { get; set; }

        public void AddSubview(IViewLayout view)
        {
            Subviews.Add(view);
            view.ParentView = this;
            view.RectTransform.localScale = Vector3.one;

            UILayout.RectFill(view.RectTransform);
        }

        public void RemoveSubview(IViewLayout view)
        {
        }

        public void Destroy()
        {
            foreach (var subview in Subviews)
            {
                subview.Destroy();
            }

            Subviews.Clear();
            Object.Destroy(UIObject);
        }
    }
}